package com.rychlickikicior.kitijdb;

import java.lang.reflect.Method;

/**
 *
 * @author kitikat
 */
class ReflectionHandler {
    private boolean underscore;

    Method getBeanReadMethod(Class entityClass, String fieldName) {
        if (entityClass == null)
            return null;
        Method result = null;
        if (underscore)
            fieldName = this.convertUnderscoreToJava(fieldName);
        String properFieldPart = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        try {
        result = entityClass.getMethod("get" + properFieldPart);
        } catch (NoSuchMethodException nsme) {
            try {
                result = entityClass.getMethod("is" + properFieldPart);
            } catch (NoSuchMethodException nsme2) {
                return this.getBeanReadMethod(entityClass.getSuperclass(), fieldName);
            }
        }
        return result;
    }

    private String convertUnderscoreToJava(String fieldName) {
        int indeks;
        while ( (indeks = fieldName.indexOf("_")) > -1) {
            char ch = fieldName.charAt(indeks+1);
            fieldName = fieldName.substring(0, indeks)+(ch+"").toUpperCase()+fieldName.substring(indeks+2);
        }
        return fieldName;
    }

    Method getBeanSetMethod(Class entityClass, String fieldName) {
        if (entityClass == null)
            return null;
        Method result = null;

        if (underscore)
            fieldName = this.convertUnderscoreToJava(fieldName);

        String properFieldPart = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        String methodName = "set" + properFieldPart;
        for (Method m : entityClass.getDeclaredMethods()) {
            if (m.getName().equals(methodName)) {
                result = m;
                break;
            }
        }
        if (result == null)
            return this.getBeanSetMethod(entityClass.getSuperclass(), fieldName);
        return result;
    }

    public boolean isUnderscore() {
        return underscore;
    }

    public void setUnderscore(boolean underscore) {
        this.underscore = underscore;
    }
}
